package com.zheng.client.util;


import javax.servlet.http.HttpServletRequest;

public class IpUtil {
    private static final String LOCAL_IP = "127.0.0.1";
    private static final ThreadLocal<String> local=new ThreadLocal<>();
    private volatile static IpUtil instance;

    public static IpUtil getInstance(){
        if(null==instance){
            synchronized (IpUtil.class){
                if(null==instance){
                    instance=new IpUtil();
                }
            }
        }
        return instance;
    }

    public void setIp(String ip){
        local.set(ip);
    }

    public void removeLocal(){
        local.remove();
    }

    public String getLocalIp(){
        return local.get();
    }
    public  String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip=LOCAL_IP;
        }

        return ip;
    }
}
